const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderDetail:'',
    id:'',
    taskTabType:1,
    commentList:'',
    taskDetail:'',
    er_confirm:false,
    ee_confirm:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id:options.id
    })
    this.taskDetail()
  },
  // 底部列表切换
  taskTabBtn:function(e){
    var { index } = e.currentTarget.dataset
    this.setData({
      taskTabType: index
    })
  },

  // 任务详情信息
  taskDetail:function(){
    var _this = this;
    var { id } = this.data;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.baseUrl + 'myTask/detail',
      data: {
        id:id,
        token: app.globalData.token
      },
      success(res) {
        wx.hideLoading()
        if (res.data.code == 1000) {
          _this.setData({
            taskDetail:res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },



  orderDetail(){
    var _this = this
    var url = app.globalData.baseUrl + 'myTask/tenderOrder';
    var { id } = this.data;
    var data = {
      id: id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxGetRequest(url, data,(res) =>{
      wx.hideLoading()
      if (res.code == 1000){
        _this.setData({
          orderDetail:res.data
        })
      _this.btnChange(res.data)
      }
    }, (err) =>{
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },

  // 操作按钮判断
  btnChange(data){
    const {role,button_add_section,button_confirm_section,button_deny_section,button_wait_section}=data

    if(role==='employer' && button_add_section && button_confirm_section){
      this.setData({
        er_confirm:true
      })
    }

    if(role==='employee' && button_deny_section && button_confirm_section){
      this.setData({
        ee_confirm:true
      })
    }

    if(button_wait_section){
      this.setData({
        ee_confirm:false,
        er_confirm:false
      })
    }
  },





  // 添加/修改付款方案
  addPayProgram(e){
    let {type} = e.target.dataset
    let {orderDetail} = this.data
    wx.navigateTo({
      url: '/taskPage/pages/addPayProgram/addPayProgram?type=' + type + '&amount=' + orderDetail.bounty + '&id=' + orderDetail.id,
    })
  },
  programEdit(e){
    let {index} = e.target.dataset
    let {orderDetail} = this.data
    let obj = orderDetail.paySections[index]
    wx.navigateTo({
      url: '/taskPage/pages/addPayProgram/addPayProgram?type=' + 'edit' + '&amount=' + orderDetail.bounty + '&obj=' + JSON.stringify(obj),
    })
  },
  // 删除阶段
  delProgram(e){
    let {id} = e.target.dataset
    let _this = this
    wx.showModal({
      title: '提示',
      content: '您确认删除该阶段吗',
      success (res) {
        if (res.confirm) {
          var url = app.globalData.baseUrl + 'myTask/delPaysection';
          var data = {
            id: id,
            token: app.globalData.token
          }
          wx.showLoading({
            title: '加载中',
          })
          app.wxPostRequest(url, data,(res) =>{
            wx.hideLoading()
            if (res.code == 1000){
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 1000
              })
              setTimeout(() => {
                _this.orderDetail()
              }, 1000);
            }
          }, (err) =>{
            wx.hideLoading()
            wx.showToast({
              title: err.data.message,
              icon: 'none',
              duration: 2000
            })
          })
        } else if (res.cancel) {}
      }
    })
  },
  // 提交服务商确认
  submitConfirm(){
    let {paySections} = this.data.orderDetail
    let percent = 0;
    let _this = this
    for(let i = 0;i < paySections.length;i++){
      percent += parseInt(paySections[i].percent)
    }
    if(percent < 100 || percent > 100){
      wx.showToast({
        title: '付款比例总和需等于100%',
        icon:'none',
        duration: 2000
      })
      return false
    }
    var url = app.globalData.baseUrl + 'myTask/confirmPaysection';
    var data = {
      task_id: this.data.id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxPostRequest(url, data,(res) =>{
      wx.hideLoading()
      if (res.code == 1000){
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1000
        })
        setTimeout(() => {
          _this.orderDetail()
        }, 1000);
      }else{
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        })
      }
    }, (err) =>{
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 托管赏金
  payTaskAmount(e){
    let {paySections} = this.data.orderDetail
    let {index} = e.target.dataset
    var url = app.globalData.baseUrl + 'pay/orderInfo';
    // 获取订单号
    var data = {
      task_id: paySections[index].task_id,
      section_id:paySections[index].id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '正在创建订单',
    })
    app.wxGetRequest(url, data, (orderRes) => {
      console.log(orderRes)
      wx.hideLoading()
      if (orderRes.code == 1000) {
        wx.navigateTo({
          url: '/taskPage/pages/pay/pay?taskid=' + paySections[index].task_id + '&title=' + paySections[index].name + '&servicePrice=' + paySections[index].price + '&section_id=' + paySections[index].id + '&code=' + orderRes.data.code + '&taskPay=1',
        })
      }else{
        wx.showToast({
          title: orderRes.message,
          icon: 'none',
          duration: 2000
        })
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 支付
  programPay(e){
    let {paySections} = this.data.orderDetail
    let {index} = e.target.dataset
    let _this = this
    var url = app.globalData.baseUrl + 'work/confirmPaySection';
    var data = {
      task_id: paySections[index].task_id,
      token: app.globalData.token,
      section_id:paySections[index].id
    }
    wx.showModal({
      title: '提示',
      content: '您确定支付吗',
      success (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          app.wxPostRequest(url, data,(res) =>{
            wx.hideLoading()
            if (res.code == 1000){
              wx.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 1000
              })
              setTimeout(() => {
                _this.orderDetail()
              }, 1000);
            }
          }, (err) =>{
            wx.hideLoading()
            wx.showToast({
              title: err.data.message,
              icon: 'none',
              duration: 2000
            })
          })
        } else if (res.cancel) {}
      }
    })
  },
  // 附件下载
  wxdown:function(event){
    var { down_url, annextype} = event.currentTarget.dataset;
    let _that = this;
    if (annextype != 'jpg' && annextype != 'png' && annextype != 'jpeg' && annextype != 'gif'){
      if (annextype != 'zip' && annextype != 'rar'){
        wx.downloadFile({
          url: down_url,
          success: function (res) {
            const tempFilePath = res.tempFilePath;
            // 保存文件
            wx.saveFile({
              tempFilePath,
              success: function (res) {
                const savedFilePath = res.savedFilePath;
                // 打开文件
                wx.openDocument({
                  filePath: savedFilePath,
                  showMenu:true,
                  success: function (res) {
                    console.log('打开文档成功')
                  },
                });
              },
              fail: function (err) {
                console.log('保存失败：', err)
              }
            });
          },
          fail: function (err) {
            console.log('下载失败：', err);
          },
        });
      }else{
        wx.showToast({
          title: '暂不支持改文件类型',
          icon: "none",
          duration: 2000
        })
      }
      return false;
    }else{
      wx.previewImage({
        current: down_url, // 当前显示图片的http链接
        urls:[
          down_url
        ]
      })
    }
   },
  //保存图片到相册，提示保存成功
   savePhoto(down_url) {
    wx.downloadFile({
     url: down_url,
     success: function (res) {
      wx.saveImageToPhotosAlbum({
       filePath: res.tempFilePath,
       success(res) {
        wx.showToast({
         title: '保存成功',
         icon: "success",
         duration: 1000
        })
       }
      })
     }
    })
  },
  // 维权
  protectionBtn:function(e){
    let {index} = e.target.dataset
    let {paySections} = this.data.orderDetail
    wx.navigateTo({
      url: '/taskPage/pages/protection/protection?taskid=' + paySections[index].task_id + '&workid=' + paySections[index].delivery.id,
    })
  },
  // 验收
  acceptanceBtn:function(e){
    let {index} = e.target.dataset
    let {paySections} = this.data.orderDetail
    if(this.data.orderDetail.teamwork == 1){
      wx.showModal({
        title: '提示',
        content: '请进入网站端订单交付工作台进行操作',
        showCancel:false
      })
      return
    }
    var _this = this
    var url = app.globalData.baseUrl + 'work/deliveryAgree';
    var data = {
      work_id: paySections[index].delivery.id,
      status: 1,
      token: app.globalData.token,
      section_id:paySections[index].id
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxGetRequest(url, data, (res) => {
      wx.hideLoading()
      if (res.code == 1000) {
        wx.showToast({
          title: '验收成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          _this.orderDetail()
        }, 2000)
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 评价
  taskEvaluation:function(){
    var { orderDetail } = this.data
    var avatar = ''
    var name = ''
    var type = ''
    if(orderDetail.role == 'employer'){
      avatar = orderDetail.wk_avatar
      name = orderDetail.wk_username
      type = 2
    }else{
      avatar = orderDetail.gz_avatar
      name = orderDetail.gz_username
      type = 1
    }
    wx.navigateTo({
      url: '/taskPage/pages/taskEvaluation/taskEvaluation?type=' + type + '&taskid=' + orderDetail.id + '&workid=' + orderDetail.jiaofu_work_id + '&avatar=' + avatar + '&title=' + name,
    })
  },
  // 评论列表
  commentList: function () {
    var _this = this
    var url = app.globalData.baseUrl + 'task/commentList';
    var { id } = this.data;
    var data = {
      id: id,
      token: app.globalData.token
    }
    wx.showLoading({
      title: '加载中',
    })
    app.wxGetRequest(url, data, (res) => {
      wx.hideLoading()
      if (res.code == 1000) {
        _this.setData({
          commentList: res.data
        })
      }
    }, (err) => {
      wx.hideLoading()
      wx.showToast({
        title: err.data.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 意见反馈
  feedback(){
    let { id } = this.data;
   /* wx.navigateTo({
      url: '/pages/programFeedback/programFeedback?id=' + id,
    })*/
    wx.navigateTo({
      url: '/userPage/pages/storeText/storeText?type=5&id='+id,
    })
  },
  // 确认付款方案
  confirmPayProgram(){
    var url = app.globalData.baseUrl + 'myTask/agreePayType';
    var { id } = this.data;
    var _this = this
    var data = {
      task_id: id,
      token: app.globalData.token
    }
    wx.showModal({
      title: '提示',
      content: '确定确认该方案吗',
      success (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          app.wxPostRequest(url, data, (res) => {
            console.log(res,'res---确认')
            wx.hideLoading()
            if (res.code == 1000) {
              _this.setData({
                ee_confirm:false,
              })
              wx.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 2000
              })
              setTimeout(function(){
                _this.orderDetail()
              },2000)
            }
          }, (err) => {
            wx.hideLoading()
            wx.showToast({
              title: err.data.message,
              icon: 'none',
              duration: 2000
            })
          })
        } else if (res.cancel) {}
      }
    })
  },
  // 交付
  programDeliver(e){
    let {index} = e.target.dataset
    let {paySections} = this.data.orderDetail
    if(this.data.orderDetail.teamwork == 1){
      wx.showModal({
        title: '提示',
        content: '请进入网站端订单交付工作台进行操作',
        showCancel:false
      })
      return
    }
    wx.navigateTo({
      url: '/taskPage/pages/submitTaskManuscript/submitTaskManuscript?id=' + paySections[index].task_id + '&jd=' + paySections[index].sort + '&section_id=' + paySections[index].id,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.orderDetail()
    // 评论列表
    this.commentList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
